﻿using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.SharePoint.Deployment;
using Microsoft.VisualStudio.SharePoint;

namespace CodeCounsel.SharePoint.DevTools.DeploymentSteps
{
    [Export(typeof(IDeploymentStep))]
    [DeploymentStep(DeploymentStepIds.ResetIIS)]
    public class ResetIIS
        : IDeploymentStep
    {
        string IISResetPath
        {
            get
            {
                return Path.Combine(
                    Environment.SystemDirectory, "iisreset.exe");
            }
        }

        public void Initialize(IDeploymentStepInfo stepInfo)
        {
            stepInfo.Name = "Reset IIS";
            stepInfo.StatusBarMessage = "Resetting IIS...";
            stepInfo.Description = "Resets the Internet Information Server.";
        }

        public bool CanExecute(IDeploymentContext context)
        {
            bool canExecute = File.Exists(IISResetPath);
            if (canExecute == false)
            {
                context.Logger.WriteLine("Skipping step because IISReset.exe can not be found.", LogCategory.Status);
            }
            return canExecute;
        }

        public void Execute(IDeploymentContext context)
        {
            ProcessStartInfo processInfo = new ProcessStartInfo(IISResetPath);
            Process process = Process.Start(processInfo);
            process.WaitForExit();
        }
    }
}
